package part2.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程池
 * 主要解决两个问题
 * 1:重用线程
 * 2:控制线程数量
 */
public class ThreadPoolDemo {
    public static void main(String[] args) {
        //创建线程池
        //创建固定大小的线程池，容量为2(内部有两条线程)
        ExecutorService pool = Executors.newFixedThreadPool(3);

        for (int i = 0; i < 5; i++) {
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    Thread t = Thread.currentThread();//获取运行该任务的线程
                    System.out.println(t.getName()+"：正在执行任务");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(t.getName()+":执行任务完毕");
                }
            };
            pool.execute(r);//将任务交个线程池
            System.out.println(Thread.currentThread().getName()+"指派一个任务给线程池");
        }
        //pool.shutdown();
        pool.shutdownNow();
        System.out.println("线程池停止了");
    }
}
